/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TorrentUI.java
 *
 * Created on Mar 6, 2012, 6:08:05 PM
 */

package my.GUI;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;
import my.ClientTorrent.ClientTorrent;
import my.ClientTorrent.FileTorrent;
import my.ClientTorrent.Torrent;

/**
 *
 * @author BAGUS
 */
public class TorrentUI extends javax.swing.JFrame {
    
    private int count = 0;
    static ClientTorrent clientTorrent;
    public static String URL = "";
    
    /** Creates new form TorrentUI */
    public TorrentUI() {
        try {
            clientTorrent = new ClientTorrent();
            initComponents();
            
            TrackerURL.getSingleton().setVisible(false);
        } catch (IOException ex) {
            Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jFileChooser2 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        IconAdd = new javax.swing.JLabel();
        IconNew = new javax.swing.JLabel();
        IconDelete = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        IconStart = new javax.swing.JLabel();
        IconPause = new javax.swing.JLabel();
        IconStop = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        IconRefresh = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        MenuAdd = new javax.swing.JMenuItem();
        MenuNew = new javax.swing.JMenuItem();
        MenuExit = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();

        jFileChooser1.setDialogTitle("Add Torrent");

        jFileChooser2.setDialogTitle("Create New Torrent");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MyTorrent");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setPreferredSize(new java.awt.Dimension(780, 40));

        IconAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/resources/file-new-icon.png"))); // NOI18N
        IconAdd.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                IconAddMouseClicked(evt);
            }
        });

        IconNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/resources/file-icon.png"))); // NOI18N
        IconNew.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                IconNewMouseClicked(evt);
            }
        });

        IconDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/resources/file-del-icon.png"))); // NOI18N
        IconDelete.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                IconDeleteMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(IconAdd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(IconNew)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(IconDelete)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(IconAdd)
                    .addComponent(IconNew)
                    .addComponent(IconDelete))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setPreferredSize(new java.awt.Dimension(780, 500));

        IconStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/resources/bt-play-icon.png"))); // NOI18N
        IconStart.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                IconStartMouseClicked(evt);
            }
        });

        IconPause.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/resources/bt-pause-icon.png"))); // NOI18N

        IconStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/resources/bt-stop-icon.png"))); // NOI18N
        IconStop.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                IconStopMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(IconStart)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(IconPause)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(IconStop)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(IconStart)
                    .addComponent(IconPause)
                    .addComponent(IconStop))
                .addGap(22, 22, 22))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        IconRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/resources/app-info-icon.png"))); // NOI18N
        IconRefresh.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                IconRefreshMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(IconRefresh)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(IconRefresh)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Torrent"));
        jPanel4.setName(""); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Nama File", "Status", "Ukuran", "Jumlah Piece", "Ukuran Piece", "Jumlah Byte Terdownload", "Persentase Terdownload"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(300);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(60);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(45);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(45);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(45);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(45);
        jTable1.getColumnModel().getColumn(6).setPreferredWidth(45);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 752, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Peer"));
        jPanel5.setPreferredSize(new java.awt.Dimension(390, 265));

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "IP", "Client", "Status"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setPreferredWidth(150);
        jTable2.getColumnModel().getColumn(1).setPreferredWidth(150);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
        );

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Log"));
        jPanel6.setPreferredSize(new java.awt.Dimension(390, 265));

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane3.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
        );

        jMenu1.setText("File");

        MenuAdd.setText("Add Torrent");
        MenuAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuAddActionPerformed(evt);
            }
        });
        jMenu1.add(MenuAdd);

        MenuNew.setText("Create New Torrent");
        MenuNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuNewActionPerformed(evt);
            }
        });
        jMenu1.add(MenuNew);

        MenuExit.setText("Exit");
        MenuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuExitActionPerformed(evt);
            }
        });
        jMenu1.add(MenuExit);

        jMenuBar1.add(jMenu1);

        jMenu3.setText("Help");

        jMenuItem4.setText("About MyTorrent");
        jMenu3.add(jMenuItem4);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE))
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel3, 0, 40, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jPanel1, jPanel2});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void MenuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuExitActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_MenuExitActionPerformed

    /**
     * Add torent Menu item 
     * @param evt 
     */
    private void MenuAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuAddActionPerformed
        // TODO add your handling code here:
        addTorrent();
    }//GEN-LAST:event_MenuAddActionPerformed

    /**
     * Add torrent to download
     */
    private void addTorrent(){
        int returnVal = jFileChooser1.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            
            FileTorrent fileTorrent;
            try {
                fileTorrent = FileTorrent.LoadFrom(file.getPath());
                JFileChooser jfc = new JFileChooser();
                jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if (jfc.showDialog(this, "Save To") != JFileChooser.APPROVE_OPTION) return;
                clientTorrent.addTorrent(fileTorrent, jfc.getSelectedFile().getPath() +"/");                                                

                Torrent torrent = clientTorrent.getListTorrent().get(count);
                System.out.println("row "+jTable1.getRowCount());                
                jTable1.setValueAt(torrent.getFileTorrent().getFilename(), count, 0);
                jTable1.setValueAt("Stopped", count, 1);
                    jTable1.setValueAt(torrent.getFileTorrent().getFileSize(), count, 2);
                    jTable1.setValueAt(torrent.getFileTorrent().getPiecesAmount(), count, 3);
                    jTable1.setValueAt(torrent.getFileTorrent().getPieceLength(), count, 4);
                    jTable1.setValueAt(torrent.getDownloaded(), count, 5);

                    long progress = torrent.getDownloaded() / torrent.getFileTorrent().getFileSize() * 100;
                    jTable1.setValueAt(progress + "%", count, 6);

                    clientTorrent.getListTorrent().get(count).cekDownloaded();
                    clientTorrent.startTorrent(count);
                    if (clientTorrent.getListTorrent().get(count).isCompleted())
                        jTable1.setValueAt("Completed", count, 1);
                    else
                        jTable1.setValueAt("Downloading", count, 1);
                count++;    
            } catch (FileNotFoundException ex) {
                Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
            }
                
        } else {
            System.out.println("File access cancelled by user.");
        }
    }
    
    /**
     * Create new torrent
     * @param evt 
     */
    private void MenuNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuNewActionPerformed
        // TODO add your handling code here:
        TrackerURL.getSingleton().setVisible(true);
        Thread  temp = new Thread(new Runnable() {

            @Override
            public void run() {
                while(TrackerURL.isWait);
                FileTorrent fileTorrent;
                try {
                    fileTorrent = FileTorrent.LoadFrom(TrackerURL.filename);
                    clientTorrent.addTorrent(fileTorrent, TrackerURL.filename.substring(0, TrackerURL.filename.lastIndexOf("\\")+1));                                                
                    Torrent torrent = clientTorrent.getListTorrent().get(count);
                    System.out.println("row "+jTable1.getRowCount());                
                    jTable1.setValueAt(torrent.getFileTorrent().getFilename(), count, 0);  
                    jTable1.setValueAt("Stopped", count, 1);
                    jTable1.setValueAt(torrent.getFileTorrent().getFileSize(), count, 2);
                    jTable1.setValueAt(torrent.getFileTorrent().getPiecesAmount(), count, 3);
                    jTable1.setValueAt(torrent.getFileTorrent().getPieceLength(), count, 4);
                    jTable1.setValueAt(torrent.getDownloaded(), count, 5);

                    long progress = torrent.getDownloaded() / torrent.getFileTorrent().getFileSize() * 100;
                    jTable1.setValueAt(progress + "%", count, 6);

                    clientTorrent.getListTorrent().get(count).cekDownloaded();
                    clientTorrent.startTorrent(count);
                    if (clientTorrent.getListTorrent().get(count).isCompleted())
                        jTable1.setValueAt("Completed", count, 1);
                    else
                        jTable1.setValueAt("Downloading", count, 1);
                    count++; 
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                
       
            }
        });
        temp.start();
    }//GEN-LAST:event_MenuNewActionPerformed

    private void IconAddMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_IconAddMouseClicked
        // TODO add your handling code here:
        addTorrent();
    }//GEN-LAST:event_IconAddMouseClicked

    private void IconNewMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_IconNewMouseClicked
        // TODO add your handling code here:
        TrackerURL.getSingleton().setVisible(true);
        Thread  temp = new Thread(new Runnable() {

            @Override
            public void run() {
                while(TrackerURL.isWait);
                FileTorrent fileTorrent;
                try {
                    fileTorrent = FileTorrent.LoadFrom(TrackerURL.filename);
                    clientTorrent.addTorrent(fileTorrent, TrackerURL.filename.substring(0, TrackerURL.filename.lastIndexOf("\\")+1));                                                
                    Torrent torrent = clientTorrent.getListTorrent().get(count);
                    System.out.println("row "+jTable1.getRowCount());                
                    jTable1.setValueAt(torrent.getFileTorrent().getFilename(), count, 0);
                    jTable1.setValueAt("Stopped", count, 1);
                    jTable1.setValueAt(torrent.getFileTorrent().getFileSize(), count, 2);
                    jTable1.setValueAt(torrent.getFileTorrent().getPiecesAmount(), count, 3);
                    jTable1.setValueAt(torrent.getFileTorrent().getPieceLength(), count, 4);
                    jTable1.setValueAt(torrent.getDownloaded(), count, 5);

                    long progress = torrent.getDownloaded() / torrent.getFileTorrent().getFileSize() * 100;
                    jTable1.setValueAt(progress + "%", count, 6);

                    clientTorrent.getListTorrent().get(count).cekDownloaded();
                    clientTorrent.startTorrent(count);
                    if (clientTorrent.getListTorrent().get(count).isCompleted())
                        jTable1.setValueAt("Completed", count, 1);
                    else
                        jTable1.setValueAt("Downloading", count, 1);
                    count++; 
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
                }       
            }
        });
        temp.start();
    }//GEN-LAST:event_IconNewMouseClicked

    /*
     * remove torrent
     * @param evt 
     */
    private void IconDeleteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_IconDeleteMouseClicked
        // TODO add your handling code here:
        DefaultTableModel test = (DefaultTableModel)jTable1.getModel();
        clientTorrent.stopTorrent(jTable1.getSelectedRow());
        clientTorrent.removeTorrent(jTable1.getSelectedRow(), false);
        test.removeRow(jTable1.getSelectedRow());
        test.addRow(new Object[8]);
        count--;
    }//GEN-LAST:event_IconDeleteMouseClicked

    private void IconStartMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_IconStartMouseClicked
        // TODO add your handling code here:
        int idx=jTable1.getSelectedRow();
        if (idx == -1) return;
        clientTorrent.getListTorrent().get(count).cekDownloaded();
        clientTorrent.startTorrent(idx);
        if (clientTorrent.getListTorrent().get(idx).isCompleted())
            jTable1.setValueAt("Completed", idx, 1);
        else
            jTable1.setValueAt("Downloading", idx, 1);
    }//GEN-LAST:event_IconStartMouseClicked

    private void IconStopMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_IconStopMouseClicked
        // TODO add your handling code here:
        int idx=jTable1.getSelectedRow();
        if (idx == -1) return;
        clientTorrent.stopTorrent(idx);
        jTable1.setValueAt("Stopped", idx, 1);
    }//GEN-LAST:event_IconStopMouseClicked

    private void clearListPeers()
    {
        for (int i = 0; i < jTable2.getRowCount();i++)
        {
            jTable2.setValueAt(null, i, 0);
            jTable2.setValueAt(null, i, 1);
            jTable2.setValueAt(null, i, 2);
        }        
    }
    private void updateDaftarPeer(int idx)
    {
////        HashMap<String, Integer> daftarPeers = clientTorrent.getListTorrent().get(idx).getListPeers();
////        HashMap<String, String> daftarStatus = clientTorrent.getListTorrent().get(idx).getStatusPeers();
//        
//        clearListPeers();
//        int i = 0;
//        for (String daftarIP : daftarPeers.keySet())
//        {
//            jTable2.setValueAt(daftarIP, i, 0);
//            jTable2.setValueAt(daftarPeers.get(daftarIP), i, 1);
//            jTable2.setValueAt(daftarStatus.get(daftarIP), i, 2);
//            i++;
//        }
    }        
    
    /**
     * update log dan peers list
     * @param evt 
     */
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        Thread temp = new Thread(new Runnable() {

            @Override
            public void run() {
                int selected = jTable1.getSelectedRow();
                if (selected != -1)
                {
                    jTextArea1.setAutoscrolls(true);
                    while (selected == jTable1.getSelectedRow())
                    {
                        // check if list torrent kosong atau tidak
                        if(!clientTorrent.getListTorrent().isEmpty()){
                            if ((selected <clientTorrent.getListTorrent().size()) && (selected >=0)){
                                if (clientTorrent.getListTorrent().get(selected).updated)
                                {
                                    jTextArea1.setText(jTextArea1.getText() + "Request : " + clientTorrent.getListTorrent().get(selected).getUrlSent() + "\n");
                                    jTextArea1.setText(jTextArea1.getText() + "Respond : \n"+ clientTorrent.getListTorrent().get(selected).getTresp().toString() + "\n");            
                                    jTextArea1.setText(jTextArea1.getText() + "==============================================================\n\n");
                                      clientTorrent.getListTorrent().get(selected).updated = false;
//                                    clientTorrent.getListTorrent().get(selected).updatePeersList();
                                    try {
                                        String result = clientTorrent.getListTorrent().get(selected).sendGetRequest(clientTorrent.getListTorrent().get(selected).genReqParam());
                                    } catch (NoSuchAlgorithmException ex) {
                                        Logger.getLogger(TorrentUI.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    
                                    updateDaftarPeer(selected);
                                }
                            }
                        }
                    }
                }
                jTextArea1.setText("");
                clearListPeers();
            }
        });
        temp.start();
    }//GEN-LAST:event_jTable1MouseClicked

    private void IconRefreshMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_IconRefreshMouseClicked
        // TODO add your handling code here:
        int selected = jTable1.getSelectedRow();
        if (selected != -1)
        {        
            try {
                clientTorrent.getListTorrent().get(selected).updateResponse();
                jTextArea1.setText(jTextArea1.getText() + "Request : " + clientTorrent.getListTorrent().get(selected).getUrlSent() + "\n");
                jTextArea1.setText(jTextArea1.getText() + "Respond : \n"+ clientTorrent.getListTorrent().get(selected).getTresp().toString() + "\n");            
                jTextArea1.setText(jTextArea1.getText() + "==============================================================\n\n");
                clientTorrent.getListTorrent().get(selected).updated = false;
                System.out.println("updated" + selected);
                updateDaftarPeer(selected);
            } catch (NoSuchAlgorithmException ex) {
                
            }
        }
    }//GEN-LAST:event_IconRefreshMouseClicked

    /**
     * Update data peer secara manual
     * @author Hartono
     */
    public void updatePeerListManual(){
         int selected = jTable1.getSelectedRow();
            System.out.println("selected " + selected);
            if (selected != -1)
            {
                // cek array kosong atau tidak
                if(!clientTorrent.getListTorrent().isEmpty()){                    
                    if ((selected <clientTorrent.getListTorrent().size()) && (selected >=0)){
                        // cek index
//                        if (clientTorrent.getListTorrent().get(selected).updated)
//                        {
                            jTextArea1.setText(jTextArea1.getText() + "Request : " + clientTorrent.getListTorrent().get(selected).getUrlSent() + "\n");
                            jTextArea1.setText(jTextArea1.getText() + "Respond : \n"+ clientTorrent.getListTorrent().get(selected).getTresp().toString() + "\n");            
                            jTextArea1.setText(jTextArea1.getText() + "==============================================================\n\n");
                            clientTorrent.getListTorrent().get(selected).updated = false;
                            System.out.println("updated" + selected);
                            updateDaftarPeer(selected);
//                        }
                    }
                }
            }
            jTextArea1.setText("");
            clearListPeers();
    }
    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TorrentUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel IconAdd;
    private javax.swing.JLabel IconDelete;
    private javax.swing.JLabel IconNew;
    private javax.swing.JLabel IconPause;
    private javax.swing.JLabel IconRefresh;
    private javax.swing.JLabel IconStart;
    private javax.swing.JLabel IconStop;
    private javax.swing.JMenuItem MenuAdd;
    private javax.swing.JMenuItem MenuExit;
    private javax.swing.JMenuItem MenuNew;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JFileChooser jFileChooser2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables

}
